package com.wss.common.wechat.controller;

import com.wss.common.context.util.SystemConfig;
import com.wss.common.wechat.exception.WeixinException;
import com.wss.common.wechat.spi.IMessageHandler;
import com.wss.common.wechat.util.aes.AesException;
import com.wss.common.wechat.util.aes.WXBizMsgCrypt;
import com.wss.common.wechat.util.weixin.DecryptUtil;
import com.wss.common.wechat.util.weixin.TokenUtil;
import com.wss.common.wechat.util.weixin.XStreamFactory;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 赵飞
 * @version V1.0
 * @Title: 用于接收微信应用级消息推送处理
 * @Package com.wss.common.wechat.controller
 * @Description:
 * @date 2017/9/5
 */
@Controller
public class WeChatOpenMsgController {

	private static Logger logger = Logger.getLogger(WeChatOpenMsgController.class);

	//消息处理相关
	@Resource(name = "appMessageHandler")
	private IMessageHandler appMessageHandler;

	/**
	 * 授权事件接收URL
	 */
	@ResponseBody
	@RequestMapping(value = "/weChat/openMsg.do",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=UTF-8")
	private String dealMag(HttpServletRequest req, HttpServletResponse resp){
		//根据获取来源判断处理当前推送XML消息处理实体

		//消息来源可靠性验证
		String timestamp = req.getParameter("timestamp");// 时间戳
		String nonce = req.getParameter("nonce");       // 随机数
		String encrypt_type = req.getParameter("encrypt_type");       // 加密算法 ase
		String msg_signature = req.getParameter("msg_signature");// 微信加密签名

		logger.info("timestamp=[" + timestamp + "];nonce=[" + nonce + "];encrypt_type=[" + encrypt_type + "];msg_signature=[" + msg_signature + "]");

		String token = SystemConfig.getComponentToken();
		String encodingAesKey = SystemConfig.getEncodingAesKey();
		String appId = SystemConfig.getComponentAppId();

		if (!TokenUtil.checkSignature(token, msg_signature, timestamp, nonce)) {
			logger.info("this msg is not from weChat Server!");
			// return "";
		}

		boolean isGet = req.getMethod().toLowerCase().equals("get");
		if(isGet){
			String echostr = req.getParameter("echostr");
			return echostr;
		}

		//获取POST流
		ServletInputStream in = null;
		String relToXml = "success";
		try {
			in = req.getInputStream();
			logger.info("接收到微信输入流,准备处理...");

			String fromAseXML = XStreamFactory.inputStream2String(in);
			logger.info("接收密文XML：\n" + fromAseXML);
			String fromXML = DecryptUtil.decryptMsg(msg_signature, timestamp, nonce, fromAseXML);
			logger.info("接收明文XML：\n" + fromXML);

			//解密后对传入XML数据进行处理：
			String toXml = appMessageHandler.invoke(fromXML);

			if(toXml!=null&&(toXml.equals("success")||toXml.equals(""))){
				logger.info("返回XML:\n"+toXml);
				return toXml;
			}

			//准备返回
			WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
			logger.info("返回明文XML:\n"+toXml);
			relToXml = pc.encryptMsg(toXml,timestamp,nonce);
			logger.info("返回密文XML:\n"+relToXml);
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("读取微信消息内容体出错！");
		} catch (AesException e) {
			logger.info("加解密微信消息内容体出错！");
			e.printStackTrace();
		} catch (WeixinException e) {
			e.printStackTrace();
		}

		return relToXml;
	}
}
